class UsersController < ApplicationController
  before_filter :require_login, :except => [:new, :create, :login, :authenticate]
  before_filter :current_user,  :except => [:new, :create, :login, :authenticate]

  # GET /users
  # GET /users.xml
  def index
    @page_title = "Users"
    @users = User.all

    @users_pending_validtation = nil
    if @current_user.administrator
      @users_pending_validation = User.where(:validated => false)
    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end

  # GET /users/1
  # GET /users/1.xml
  def show
    @user = User.find(params[:id])
    @page_title = "User Details for #{@user.username}"

    @events = Event.paginate :per_page => 10, :page => params[:page],
                             :order => 'begin_date DESC' 

    @owned_events   = Event.paginate :per_page => 10,
                                     :page => params[:owned_events_page],
                                     :order => 'begin_date DESC',
                                     :conditions => ["owner_id = ?", @user.id]

    @created_events = Event.paginate :per_page => 10,
                                     :page => params[:created_events_page],
                                     :order => 'begin_date DESC',
                                     :conditions => ["creator_id = ?", @user.id]

    @next_event = (Event.where("owner_id == :id AND begin_date >= :date AND event_type < 5",
                               :date => Date.today, :id => @user.id).sort_by {|e| e.begin_date}).first
    

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/new
  # GET /users/new.xml
  def new
    @page_title = "New User"
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
      format.js
    end
  end

  # GET /users/1/edit
  def edit
    @page_title = "Edit User"
    @user = User.find(params[:id])
    authorize_modification_of_user @user
  end

  # POST /users
  # POST /users.xml
  # Note: model validates uniqueness of user
  def create
    @page_title = "Create User"

    if User.exists?(:email => params[:email])
      flash[:error] = "Username already registered"
      redirect_to :back
      return
    end

    if !Auth.auth_ldap(params[:email], params[:password])
      flash[:error] = "Incorrect username/password or Bluepages communication error"
      redirect_to :back
      return
    end

    @user = User.new

    name = BluePages.get_first_last_name(params[:email])
    
    @user.username = name[0][0] + ". " + name[1].capitalize  #First initial + last name
    @user.email    = params[:email]
    @user.uid      = BluePages.get_uid(params[:email])

    # users cannot make themselves admin or validate themselves,
    # disable any user forged parameter settings which violate this rule
    @user.administrator = false 
    @user.validated     = false

    @user.alloted_vacation_days = 20
    @user.alloted_pc_days = 4

    @user.right = Right.create

    user_saved = @user.save && @user.right.save
    
    #login user
    if user_saved
      session[:user_id] = @user.id
      session[:user_ip] = request.remote_ip
    end

    respond_to do |format|
      if user_saved 
        format.html { redirect_to(@user, :notice => 'User was successfully created. Awaiting validation by admin.') }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
    @page_title = "Update User"

    @user = User.find(params[:id])
    authorize_modification_of_user @user

    # Enforce security policies
    if !@current_user.administrator && !@user.administrator
      params[:user][:administrator] = false
    end

    if !@current_user.administrator && !@user.validated
      params[:user][:validated] = false
    end

    @user.save

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to(@user, :notice => 'User was successfully updated.') }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.xml
  def destroy
    @page_title = "Destroy User"

    if (params[:id])
      flash[:error] = "Cannot delete user id 1, Admin"
      redirect_to :back
      return
    end

    @user = User.find(params[:id])
    authorize_modification_of_user @user
    @user.destroy

    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end

  def login
    @page_title = "Login"
    if logged_in?
      redirect_to current_user, :notice => "Already logged in."
      return
    end

    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

  def import
    @page_title = "Import"

    if params[:uploaded]

    respond_to do |format|
      format.html
    end
  end

  def authenticate
    @page_title = "Authenticate User"

    respond_to do |format|
      user = User.where(:email => params[:email]).first
      if user.nil?
        flash[:error] = "User specified does not exist.  Please register"
        redirect_to new_user_path
        return
      elsif Auth.auth_ldap(params[:email], params[:password]) 
        reset_session
        session[:user_id] = user.id
        session[:user_ip] = request.remote_ip
        format.html { redirect_to(user, :notice => "Welcome #{user.username}.") }
      else
        flash[:error] = "Incorrect username/password"
        format.html { redirect_to(login_users_path) }
      end
    end
  end

  def logout
    session[:user_id] = nil
    reset_session
    respond_to do |format|
      format.html { redirect_to(calendar_url, :notice => 'User was successfully logged out.') }
      format.xml  { render :xml => @user }
    end
  end

  def authorize_modification_of_user(user)
    unless logged_in? && (@current_user.id == user.id || @current_user.administrator)
      flash[:error] = "User does not have rights to edit the requested user's details" 
      redirect_to :back
    end
  end

  def validate
    @user = User.find(params[:id])

    if !@current_user.administrator
      flash[:error] = "Only administrators can validate new users"
      redirect_to :back
      return
    end

    @user.validated = true

    respond_to do |format|
      if @user.save
        format.html { redirect_to(@user, :notice => 'User was successfully validated.') }
        format.xml  { render :xml => @user, :status => :validated, :location => @user }
      else
        format.html { render :action => "validate" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end


end
